﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;
using Furion.RemoteRequest.Extensions;
using Furion;

namespace Admin.NET.Application
{
    /// <summary>
    /// 转储单服务
    /// </summary>
    [ApiDescriptionSettings("转储单", Name = "WmsDumpOrder", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsDumpOrderService : IWmsDumpOrderService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsDumpOrder,MasterDbContextLocator> _wmsDumpOrderRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly IRepository<WmsDumpOrderDetails, MasterDbContextLocator> _wmsDumpOrderDetailsRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();
        private readonly IRepository<WmsOrderType, MasterDbContextLocator> _wmsOrderTypeRep;


        public WmsDumpOrderService(
            IRepository<WmsDumpOrder,MasterDbContextLocator> wmsDumpOrderRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,IRepository<WmsDumpOrderDetails, MasterDbContextLocator> wmsDumpOrderDetailsRep
            , ISysExcelTemplateService sysExcelTemplateService
            , IRepository<WmsOrderType, MasterDbContextLocator> wmsOrderTypeRep

        )
        {
            _wmsDumpOrderRep = wmsDumpOrderRep;
         _sysDictTypeRep = sysDictTypeRep;
         _sysDictDataRep = sysDictDataRep;
         _sysExcelTemplateService = sysExcelTemplateService;
            _wmsDumpOrderDetailsRep = wmsDumpOrderDetailsRep;
            _wmsOrderTypeRep = wmsOrderTypeRep;
        }

        /// <summary>
        /// 分页查询转储单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsDumpOrderOutput>> Page([FromQuery] WmsDumpOrderSearch input)
        {
            var wmsDumpOrders = await _wmsDumpOrderRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.NO), u => EF.Functions.Like(u.NO, $"%{input.NO.Trim()}%"))
                                     .Where(input.Billdate != null, u => u.Billdate == input.Billdate)
                                     .Where(!string.IsNullOrEmpty(input.Creator), u => EF.Functions.Like(u.Creator, $"%{input.Creator.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Companyname), u => EF.Functions.Like(u.Companyname, $"%{input.Companyname.Trim()}%"))
                                     .Where(input.OrderStatus != null, u => u.OrderStatus == input.OrderStatus)
                                     .OrderBy(PageInputOrder.OrderBuilder<WmsDumpOrderSearch>(input))
                                     .ProjectToType<WmsDumpOrderOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsDumpOrders;
        }

        /// <summary>
        /// 获取单据明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("PageDetail")]
        public async Task<PageResult<DumpPageDetailOutput>> PageDetail([FromQuery] DumpPageDetailInput input)
        {
            var wmsOrders = await _wmsDumpOrderDetailsRep.DetachedEntities
                                     .Where(input.Id != null, u => u.OrderId == input.Id)
                                     .ProjectToType<DumpPageDetailOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }

        /// <summary>
        /// 增加转储单(yigo系统获取)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("GetDumpOrder")]
        [UnitOfWork]
        public async Task GetDumpOrder()
        {
            //获取入库通知单
            string url = App.Configuration["YiGoWebApi:QueryAllocate"];
            var Billdate_S = DateTime.Now.AddDays(-15).ToString("yyyy-MM-dd");
            var Billdate_E = DateTime.Now.AddDays(15).ToString("yyyy-MM-dd");
            //写日志文件
            //Log.Error($"[TransferContainerCode][ContainerCode:{input.ContainerCode}][url:{url}]");
            var response = await url.SetHttpMethod(System.Net.Http.HttpMethod.Post)
                                    .SetBody(new Dictionary<string, object> {
                                            { "Billdate_S", Billdate_S },
                                            { "Billdate_E", Billdate_E},
                                    }, "application/json").PostAsStringAsync();
            var Data = response.FromJson<WmsDumpOrderOutputByYiGO>();
            var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("转储"));
            foreach (var item in Data.Data)
            {
                item.Id = Yitter.IdGenerator.YitIdHelper.NextId();
                var wmsDumpOrder = item.Adapt<WmsDumpOrder>();
                //判断是否存在相同的单据号
                var isExcit = await _wmsDumpOrderRep.AnyAsync(x => x.NO == item.NO);
                if (!isExcit)
                {
                    wmsDumpOrder.OrderLargeCategory = wmsOrderType != null ? wmsOrderType.Pid : 0;
                    wmsDumpOrder.OrderSubclass = wmsOrderType != null ? wmsOrderType.Id : 0;
                    await _wmsDumpOrderRep.InsertNowAsync(wmsDumpOrder);
                    foreach (var item1 in item.Dtls)
                    {
                        var wmsDumpOrderDeatail = item1.Adapt<WmsDumpOrderDetails>();
                        wmsDumpOrderDeatail.OrderId = item.Id;
                        await _wmsDumpOrderDetailsRep.InsertNowAsync(wmsDumpOrderDeatail);
                    }
                }
            }
        }

        /// <summary>
        /// 执行转储单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("ExecuteDumpOrder")]
        public async Task ExecuteDumpOrder([FromQuery] DumpPageDetailInput input)
        {
            var wmsOrders = await _wmsDumpOrderDetailsRep.DetachedEntities
                                     .Where(input.Id != null, u => u.OrderId == input.Id)
                                     .ProjectToType<DumpPageDetailOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
        }
    
        /// <summary>
        /// 不分页查询转储单列表
        /// </summary>
        /// <param name="input">转储单查询参数</param>
        /// <returns>(转储单)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsDumpOrderOutput>> ListNonPageAsync([FromQuery] WmsDumpOrderSearchNonPage input)
        {
            var pNO = input.NO?.Trim() ?? "";
            var pBilldate = input.Billdate;
            var pCreator = input.Creator?.Trim() ?? "";
            var pCompanyname = input.Companyname?.Trim() ?? "";
            var pOrderStatus = input.OrderStatus;
            var wmsDumpOrders = await _wmsDumpOrderRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pNO), u => EF.Functions.Like(u.NO, $"%{pNO}%")) 
                .Where(pBilldate != null, u => u.Billdate == pBilldate)
                .Where(!string.IsNullOrEmpty(pCreator), u => EF.Functions.Like(u.Creator, $"%{pCreator}%")) 
                .Where(!string.IsNullOrEmpty(pCompanyname), u => EF.Functions.Like(u.Companyname, $"%{pCompanyname}%")) 
                .Where(pOrderStatus != null, u => u.OrderStatus == pOrderStatus)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsDumpOrderOutput>()
            .ToListAsync();
            return wmsDumpOrders;
        }


        /// <summary>
        /// 增加转储单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWmsDumpOrderInput input)
        {
            var wmsDumpOrder = input.Adapt<WmsDumpOrder>();
            await _wmsDumpOrderRep.InsertAsync(wmsDumpOrder);
        }

        /// <summary>
        /// 删除转储单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsDumpOrderInput input)
        {
            var wmsDumpOrder = await _wmsDumpOrderRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsDumpOrderRep.DeleteAsync(wmsDumpOrder);
        }

        /// <summary>
        /// 更新转储单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsDumpOrderInput input)
        {
            var isExist = await _wmsDumpOrderRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsDumpOrder = input.Adapt<WmsDumpOrder>();
            await _wmsDumpOrderRep.UpdateAsync(wmsDumpOrder,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取转储单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsDumpOrderOutput> Get([FromQuery] QueryeWmsDumpOrderInput input)
        {
            return (await _wmsDumpOrderRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsDumpOrderOutput>();
        }

        /// <summary>
        /// 获取转储单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsDumpOrderOutput>> List([FromQuery] WmsDumpOrderInput input)
        {
            return await _wmsDumpOrderRep.DetachedEntities.ProjectToType<WmsDumpOrderOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入转储单功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsDumpOrder", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<WmsDumpOrderOutput> wmsDumpOrderList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsDumpOrderOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wmsDumpOrderList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsDumpOrder>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsDumpOrder, WmsDumpOrderOutput>(selectKeys);
            List<WmsDumpOrder> updates = new();
            List<WmsDumpOrder> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wmsDumpOrderExistSubList = _wmsDumpOrderRep.Where(filter).Select(selector).ToList();
                    wmsDumpOrderExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var wmsDumpOrder in wmsDumpOrderList) 
                {
                    if (wmsDumpOrder.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wmsDumpOrder.Adapt<WmsDumpOrder>());
                    }
                    else 
                    {
                        adds.Add(wmsDumpOrder.Adapt<WmsDumpOrder>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wmsDumpOrderRep.Update(x));
                

                var maxId = _wmsDumpOrderRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<WmsDumpOrder>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载转储单的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsDumpOrder", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据转储单查询参数导出Excel
        /// </summary>
        /// <param name="input">转储单查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WmsDumpOrderSearchNonPage input)
        {
            var wmsDumpOrderList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wmsDumpOrderList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsDumpOrder", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
